<?php
/*  vim: set expandtab shiftwidth=4 softtabstop=4 tabstop=4:    */

class Auth_DB {
    private static $sql;

    public function setAuthQuery($table, $fields = NULL, $where = NULL) {
        $sql    =   "SELECT ";

        if(!isset($fields) || empty($fields) || $fields === NULL) {
            $sql    .=   "* ";
        } else {
            $sql    .=  "$fields ";
        }

        $sql    .=  "FROM $table ";

        if(isset($where) && !empty($where) && $where !== NULL) {
            $sql    .=  "WHERE $where";
        }

        self::$sql  =   $sql;
    }

    public function query() {
        if(($res = DB::$db->query(self::$sql)) !== FALSE) {
            return $res;
        } else {
            return FALSE;
        }
    }

    public function verifyPassword($userInput) {
        if(($storedInput = self::query()) !== FALSE) {
            if($userInput == $storedInput) {
                return TRUE;
            } else {
                throw new Exception("Authorization failed; Password incorrect");
            }
        } else {
            throw new Exception("Authorization failed; Query failure");
        }
    }

    public function verifyUser($username, $password) {
        $config     =   self::checkConfigs();
        self::$sql  =   "SELECT $config[idField] FROM $config[usersTable] WHERE $config[usernameField] = '$username' ".
                        "AND $config[passwordField] = '$password'";

        if(self::query() === FALSE) {
            return FALSE;
        }
    }
        
    /*  checkConfigs()                                                      :   Check the configurations to verify everything is set
     *
     *  @access public
     */
    public function checkConfigs() {
        $config     =   Control::getConfigs();

        if(isset($config['auth']['db']) && !empty($config['auth']['db']) && is_array($config['auth']['db'])) {
            $requriedFields     =   array("usersTable", "idField", "usernameField", "passwordField");

            foreach($requiredFields as $field => $value) {
                if(!isset($config['auth']['db'][$field]) || empty($config['auth']['db'][$field])) {
                    throw new Exception("Configurations incomplete.  '$field' unset");
                }
            }

            return $config['auth']['db'];
        } else {
            throw new Exception("No configurations for DB authorization");
        }
    }

}
?>
